package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryKitchenResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import java.util.Calendar

// 菜菜厨房工作
class KitchenWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "菜菜厨房"

    override val priority: Int
        get() = 8

    override val isActWork: Boolean
        get() = true
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询菜菜厨房信息
            val queryResult = gameApi.queryKitchen()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 2. 判断是否可以领取
                    if (canClaimKitchen(response)) {
                        // 3. 领取体力
                        val claimResult = gameApi.claimKitchen()
                        claimResult.foldWithApiException(
                            onSuccess = { claimResponse ->
                                historyManager.addHistory(name, claimResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 判断是否可以领取菜菜厨房体力
     * 根据注释：12-14、18-20、22-24点均可领体力
     */
    private fun canClaimKitchen(response: QueryKitchenResponse): Boolean {
        // 首先检查type，为-1则不能领，大于0可以领
        if (response.type == -1) {
            return false
        }
        
        // 检查当前时间是否在可领取时间段内
        val calendar = Calendar.getInstance()
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        
        return when (hour) {
            in 12..14 -> true  // 12-14点
            in 18..20 -> true  // 18-20点
            in 22..23 -> true  // 22-24点
            else -> false
        }
    }
}